<template>
  <div id="app">
    <div class="container">
      <div class="sidebar">
        <header class="header">
          <input type="text" v-model="searchQuery" placeholder="搜索文件或文件夹" class="search-input" />
          <button @click="selectFolder">选择文件夹</button>
        </header>
        <FileTree :data="filteredData" @fileSelected="onFileSelected" />
      </div>
      <div class="main-content">
        <ImageViewer :file="base64Image" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import FileTree from '../components/FileTree.vue';
import ImageViewer from '../components/ImageViewer.vue';
import {ElMessage} from "element-plus";

const selectFolder = () => {
  window.pywebview.api.select_folder().then(response => {
    window.pywebview.api.list_files_and_folders().then(response => {
                // alert(response);              
      fileData.value = JSON.parse(response);
    });        
  });          
};


const fileData = ref([]);
const searchQuery = ref('');
const selectedFile = ref(null);
let base64Image = ref(null);

const onFileSelected = (file) => {
  console.log('File selected:', file); // 添加日志以便调试
  // fileService.base64StrFromFile("");
  selectedFile.value = file;
  window.pywebview.api.base64_str_from_file(file.path).then(response => {
    // alert(response);
    base64Image.value = response;
  });

  // ElMessage('这是一条消息' + base64Image);
};

const filterData = (data, query) => {
  if (!query) return data;

  const lowerCaseQuery = query.toLowerCase();

  const filterItem = (item) => {
    const matches = item.name.toLowerCase().includes(lowerCaseQuery);
    if (matches) {
      return { ...item, expanded: true };
    }

    if (item.children) {
      const filteredChildren = filterData(item.children, query);
      if (filteredChildren.length > 0) {
        return { ...item, children: filteredChildren, expanded: true };
      }
    }

    return null;
  };

  return data.map(filterItem).filter(Boolean);
};

function getData() {
  // let obj1 = javaConnector.toLowerCase("1b")
  let obj = fileService.getFileData()
  fileData.value = JSON.parse(obj);
}


const filteredData = computed(() => filterData(fileData.value, searchQuery.value));
</script>


<style>
/*#app {
  display: flex;
  flex-direction: column;
  height: 100vh;
}*/
.search-input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
.container {
  display: flex;
  width: 100%;
}

.sidebar {
  width: 30%;
  border-right: 1px solid #ccc;
  padding: 10px;
  overflow-y: auto;
  height: 100%;
}

.main-content {
  width: 70%;
  padding: 10px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: auto; /* 确保用户可以选择内容 */
  -webkit-user-drag: auto; /* 确保用户可以拖动内容 */
}
</style>
